# -*- coding:utf-8 -*-

from flask import Flask,render_template,request,redirect,url_for,make_response,abort
from werkzeug.routing import BaseConverter  #自定义路由的正则表达式1:引入BaseConverter
from werkzeug.utils import secure_filename
from flask.ext.script import Manager
from os import path


# 自定义路由正则表达式2:定义RegexConverter类,继承BaseConverter
class RegexConverter(BaseConverter):
    def __init__(self,url_map,*items):
        super(RegexConverter,self).__init__(url_map)
        self.regex=items[0]

app = Flask(__name__)
app.url_map.converters['regex']=RegexConverter  #自定义路由的正则表达式3:实例化一个对象,'regex'为对象的别名
manager = Manager(app)


@app.route('/')
def hello_world():  # 视图函数
    response = make_response(render_template('index.html',title='<h1>Welcome</h1>'))
    # 设置cookie的方法:
    # 通过response对返回的对象进行包装,调用response.set_cookie(要设置的内容)
    response.set_cookie('username','')

    return response #可以输出html标签

@app.route('/services')
def services():
    return 'Services'

@app.route('/about')  #路由后面没有斜杠'/',在浏览器中也不能输入'/',相当于访问的是个文件file
def about():
    return 'About'

@app.route('/user/<regex("[a-z]{3}"):user_id>') #可以接受三种转换器int,float,path:匹配地址,如用正则表达式,需要自定义;
def user(user_id):
    return 'User %s'%user_id


@app.route('/projects/')  #加斜杠相当于访问的是个文件夹,在浏览器中输入可以省略'/'
@app.route('/our_works')  #可以给一个地址加入两个路由;
def projects():
    return 'The project page'

@app.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'POST':
        # post请求获取form提交的信息;
        username = request.form['username']
        password = request.form['password']
    else:
        # get请求获取form提交的信息;
        request.args['username']
    return render_template('login.html',method=request.method)

@app.route('/upload',methods=['GET','POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']  #此处的'file'要和form表单中file的name属性一致
        basepath = path.abspath(path.dirname(__file__))
        upload_path = 'C:\Users\Administrator\Desktop'
        print upload_path,'>>>>>>>>>>>>>>>>>>>>>>>>>>'
        f.save(upload_path,secure_filename(f.filename))
        return redirect(url_for('upload'))
    return render_template('upload.html')

@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'),404

@manager.command
def dev():
    from livereload import Server
    live_server = Server(app.wsgi_app)
    live_server.watch('**/*.*')
    live_server.serve(open_url=True)


if __name__ == '__main__':
    #app.run(debug=True)
    app.debug = True
    manager.run()
